/*
 * GWT-Ext Widget Library
 * Copyright 2007 - 2008, GWT-Ext LLC., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 3 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
 
package com.hod.client.reserves;

import com.google.gwt.core.client.GWT;
import com.google.gwt.gears.client.database.DatabaseException;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.data.ArrayReader;
import com.gwtext.client.data.DateFieldDef;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.FloatFieldDef;
import com.gwtext.client.data.IntegerFieldDef;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.widgets.PagingToolbar;
import com.gwtext.client.widgets.ToolTip;
import com.gwtext.client.widgets.Window;
import com.gwtext.client.widgets.form.Field;
import com.gwtext.client.widgets.form.NumberField;
import com.gwtext.client.widgets.form.event.FieldListenerAdapter;
import com.gwtext.client.widgets.grid.BaseColumnConfig;
import com.gwtext.client.widgets.grid.CellMetadata;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.Renderer;
import com.gwtext.client.widgets.menu.BaseItem;
import com.gwtext.client.widgets.menu.Item;
import com.gwtext.client.widgets.menu.event.BaseItemListenerAdapter;
import com.gwtextux.client.data.PagingMemoryProxy;
import com.hod.client.backend.orm.client.GearsDataStore;
import com.hod.client.backend.orm.client.GearsQuery;
import com.hod.client.client.Client;
import com.hod.client.frontend.AbstractGrid;
import com.hod.client.lodging.LodgingCRUD;
import com.hod.client.lodging.LodgingRecordset;
import com.hod.client.room.Room;
import com.hod.client.room.RoomCRUD;
import com.hod.client.room.RoomRecordset;

public class ReservationGrid extends AbstractGrid {
	
	private GearsDataStore dsClient = null;
    
    
    private Renderer rndrClient = new Renderer() {
        public String render(Object value, CellMetadata cellMetadata, Record record, int rowIndex, int colNum, Store store) {
        	Client o;
			try {
				o = (Client)dsClient.findById(new Integer(record.getAsString("idClient")));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				return "";
			} catch (DatabaseException e) {
				// TODO Auto-generated catch block
				return "";
			} 
            return o.getName()+" "+o.getSurname();
        }
    };
    
    private Renderer rndrReservationState = new Renderer() {
        public String render(Object value, CellMetadata cellMetadata, Record record, int rowIndex, int colNum, Store store) {
        	ReservationState o;
			try {
				GearsDataStore ds = (GearsDataStore) GWT.create(ReservationState.class);
				o = (ReservationState)ds.findById(new Integer(record.getAsString("idReservationState")));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				return "";
			} catch (DatabaseException e) {
				// TODO Auto-generated catch block
				return "";
			} 
            return o.getName();
        }
    };


    private static RecordDef recordDef = new RecordDef(
            new FieldDef[]{
                    new StringFieldDef("idReservation"),
                    new StringFieldDef("codeReservation"),
                    new DateFieldDef("dateReservation"),
                    new IntegerFieldDef("idRoomType"),
                    new IntegerFieldDef("idReservationState"),
                    new IntegerFieldDef("idClient"),
                    new DateFieldDef("expiration"),
                    new FloatFieldDef("beck"),
                    new IntegerFieldDef("paxCount"),
                    new IntegerFieldDef("dayCount")                    
               }
    );

	

	public ReservationGrid() {      
    }

    public ReservationGrid(boolean small,GearsDataStore ds,String idRoom) {
    	this.ds = ds;
    	this.dsClient = (GearsDataStore) GWT.create(Client.class);
    	columns = new BaseColumnConfig[]{
                new ColumnConfig("codeReservation", "codeReservation", 60, true, null, "codeReservation"),    	
                new ColumnConfig("dateReservation", "dateReservation", 60, true, null, "dateReservation"),
                new ColumnConfig("idClient", "idClient", 60, true,rndrClient, "idClient"),
                new ColumnConfig("idReservationState", "idReservationState", 60, true,rndrReservationState, "idReservationState"),
                new ColumnConfig("expiration", "expiration", 60, true, null, "expiration"),
                new ColumnConfig("beck", "beck", 60, true, null, "beck")
        };
    	
    	getData(idRoom);

        ColumnModel columnModel = getColumnConfigs();
        setColumnModel(columnModel);

        setFrame(true);
        setStripeRows(true);
        setIconCls("grid-icon");      

        createPopUp();
        createPager(); 
    }
    protected void getData(){    	
    	getData("");
    }
    
    protected void getData(String idRoom){
    	PagingMemoryProxy proxy = null;
		try {
			GearsQuery q = null;
			if (idRoom.length()<=0)
			    q = this.ds.getNamedQuery(Reservation.FIND_ALL);
			else
			{ 
				q = this.ds.getNamedQuery(Reservation.FIND_BY_ROOM);
				q.setString(0, idRoom);
			}
			Reservation[] data = (Reservation[]) q.execute();
			Reservation rs = null;
			Object[][]data2 = new Object[data.length][];
			for (int i = 0; i < data.length; i++) {
                rs = data[i];	               
                data2[i] = new Object[]{rs.getIdReservation(),rs.getCodeReservation(),rs.getDateReservation(),rs.getIdRoomType(),rs.getIdReservationState(),rs.getIdClient(),rs.getExpiration(),rs.getBeck(),rs.getPaxCount(),rs.getDayCount(),rs.getIdRoom(),rs.getIdBed()};
            }
			proxy = new PagingMemoryProxy(data2);
			
			
		} catch (DatabaseException e) {
			// TODO Auto-generated catch block
			//Window.alert(e.getMessage());
		} 

        ArrayReader reader = new ArrayReader(recordDef);
        store = new Store(proxy, reader);
        store.load(0,numberRecords);
        setStore(store);
    }
           
    protected void createGridMenu() { 
    	super.createGridMenu();
    	gridMenu.addItem(new Item("Check-in",new BaseItemListenerAdapter() { 
	           public void onClick(BaseItem item, EventObject e) { 
	        	   if (!LodgingRecordset.existsLodgingForClient(getSelectionModel().getSelected().getAsString("idClient"))){
	        		   try {
						Window checkin = new Window();
						   LodgingCRUD lodCRUD = new LodgingCRUD();
						   //Filtro por tipo de habitacion solicitada en la reserva
						   lodCRUD.setRooms(RoomRecordset.getFreeRoomsByType(getSelectionModel().getSelected().getAsString("idRoomType"))); 
						   checkin.add(lodCRUD.createFormPanel());
						   lodCRUD.setIdClient(getSelectionModel().getSelected().getAsInteger("idClient"));
						   lodCRUD.setIdReservation(getSelectionModel().getSelected().getAsInteger("idReservation"));
						   //HODScreenManager.lodgings.setIdClient(getSelectionModel().getSelected().getAsInteger("idClient"));
						   //checkin.add(HODScreenManager.lodgings.createFormPanel());
						   checkin.show();
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						com.google.gwt.user.client.Window.alert(e1.getMessage());
					}	        		   
	        	   }
	        	} 
	         }));  
    }
    
}
